﻿
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Librarinth;
//using SkinnedModel;


namespace SunwellRenderer.Rendering
{
	public class StaticShadowRenderer : Renderer
	{
		protected override IEnumerable<string> AllInitialShader
		{ get { yield return typeof(ShadowShader).Name; } }

		public readonly int ShadowMapIndex;
		public StaticShadowRenderer()
		{
			Parent.AllGlobalTexture.GetIndex("Shadow",out ShadowMapIndex);
		}

		public readonly Vector3 LightDir = Vector3.Forward;
		protected override void OnLoadContent()
		{
			var device	= SunwellMain.Instance.GraphicsDevice;

			SurfaceFormat[] shadowMapFormats =
			{
				SurfaceFormat.HalfSingle,
                SurfaceFormat.Single,
			};

			var shadowMapFormat = SurfaceFormat.Unknown;
			var adapter	= GraphicsAdapter.DefaultAdapter;
			foreach(var surfaceFormat in shadowMapFormats)
			{
				var supported = adapter.CheckDeviceFormat(DeviceType.Hardware
					,adapter.CurrentDisplayMode.Format,TextureUsage.Linear,QueryUsages.None
					,ResourceType.RenderTarget,surfaceFormat);

				if(supported)
				{
					shadowMapFormat = surfaceFormat;
					break;
				}
			}

			var Size	= 512;
			Shadow	= new RenderTarget2D(device,Size,Size,1,shadowMapFormat);

			if(adapter.CheckDepthStencilMatch(DeviceType.Hardware,adapter.CurrentDisplayMode.Format,shadowMapFormat,DepthFormat.Depth16))
				depthBuffer = new DepthStencilBuffer(device,Size,Size,DepthFormat.Depth16);
			else depthBuffer = new DepthStencilBuffer(device,Size,Size,DepthFormat.Unknown);
		}

		RenderTarget2D Shadow;
		DepthStencilBuffer depthBuffer;
		DepthStencilBuffer oldDepthStencilBuffer;
		protected override void Begin(GraphicsDevice device)
		{
			device.RenderState.DepthBufferWriteEnable = true;
			device.RenderState.DepthBufferEnable = true;

			oldDepthStencilBuffer = device.DepthStencilBuffer;
			device.DepthStencilBuffer = depthBuffer;

			device.SetRenderTarget(0,Shadow);
			device.Clear(Color.TransparentWhite);
		}
		protected override void End(GraphicsDevice device)
		{
			device.SetRenderTarget(0,null);
			Parent.AllGlobalTexture.Datas[ShadowMapIndex]	= Shadow.GetTexture();

			device.DepthStencilBuffer	= oldDepthStencilBuffer;
		}
	}
}